import java.util.*;

public class TreeCode {

    public static class TreeNode {
        char val;
        TreeNode right;
        TreeNode left;
        public TreeNode(char val) {
            this.val = val;
        }
    }
    public TreeNode crateTree() {
        TreeNode nodeA = new TreeNode('A');
        TreeNode nodeB = new TreeNode('B');
        TreeNode nodeC = new TreeNode('C');
        TreeNode nodeD = new TreeNode('D');
        TreeNode nodeE = new TreeNode('E');
        TreeNode nodeF = new TreeNode('F');
        TreeNode nodeG = new TreeNode('G');
        TreeNode nodeH = new TreeNode('H');

        nodeA.left = nodeB;
        nodeA.right = nodeC;

        nodeB.left = nodeD;
        nodeB.right = nodeE;

        nodeE.right = nodeH;

        nodeC.left = nodeF;
        nodeC.right = nodeG;

        return nodeA;
    }
    public void preOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }

    /**
     * 检查一棵二叉树是否为深度平衡二叉树
     * @param root
     * @return
     */
    //https://leetcode.cn/problems/balanced-binary-tree/
    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }
        return getHeight(root) >= 0;
    }

    public int getHeight(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftH = getHeight(root.left);
        if(leftH < 0) {
            return -1;
        }
        int rightH = getHeight(root.right);

        if(leftH >=0 && rightH >= 0 && Math.abs(leftH-rightH) < 2) {
            return Math.max(leftH,rightH) + 1;
        }else {
            return -1;
        }
    }

    /**
     * 检查一棵树是否对称
     * @param root
     * @return
     */
    //
    public boolean isSymmetric(TreeNode root) {
        if(root == null) {
            return true;
        }
        return isSame(root.left,root.right);
    }
    public boolean isSame(TreeNode leftTree,TreeNode rightTree) {
        //1.结构不一样
        if(leftTree == null && rightTree != null) return false;
        if(leftTree != null && rightTree == null) return false;

        if(leftTree == null && rightTree ==null) return true;

        //2.值不相等
        if(leftTree.val != rightTree.val) return false;
        //继续判断第二层
        if(isSame(leftTree.left,rightTree.right) && isSame(leftTree.right,rightTree.left)) {
            return true;
        }
        return false;
    }
    /**
     * 用前序遍历构建二叉树
     */
    public  int i = 0;
    public  TreeNode createTree(String str) {
        TreeNode root = null;//创建一个结点
        char ch = str.charAt(i);
        if(ch != ' ') {
            root = new TreeNode(ch);//给根节点赋值
            i++;
            root.left = createTree(str);
            root.right = createTree(str);

        }else {
            i++;
        }
        return root;
    }

    /**
     * 前序
     * @param root
     */
    public void inorder(TreeNode root) {//中
        if(root == null) {
            return;
        }
        inorder(root.left);
        System.out.print(root.val+" ");
        inorder(root.right);
    }
    public void postorder(TreeNode root) {//后
        if(root == null) {
            return;
        }
        postorder(root.left);
        postorder(root.right);
        System.out.print(root.val+" ");

    }
    /**
     * 层序遍历
     */
    public void levelOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();//使用队列遍历
        queue.offer(root);//存入结点
        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();//弹出结点
            System.out.print(cur.val+" ");
            if(cur.left != null) {
                queue.offer(cur.left);
            }
            if(cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }
    public List<List<Character>> levelOrder2(TreeNode root) {
        List<List<Character>> listTree = new LinkedList();
        if(root == null) {
            return listTree;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            int size = queue.size();//记录大小
            List<Character> list = new LinkedList<>();
            while(size != 0) {
                TreeNode cur = queue.poll();
                size--;
                list.add(cur.val);
                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            listTree.add(list);
        }

        return listTree;
    }

    /**
     * 求公共祖先
     * @param root
     * @param node
     * @param stack
     * @return
     */
    public boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
        if(root == null) {
            return false;
        }
        stack.push(root);
        if(root == node) {
            return true;
        }
        boolean flgLeft = getPath(root.left,node,stack);
        if(flgLeft) {
            return true;
        }
        boolean flgRight = getPath(root.right,node,stack);
        if(flgRight) {
            return true;
        }
        stack.pop();
        return false;
    }
    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return null;
        }
        //1.将路径存入栈中
        Stack<TreeNode> stack1 = new Stack<>();
        getPath(root,p,stack1);
        Stack<TreeNode> stack2 = new Stack<>();
        getPath(root,q,stack2);
        //2.将大的栈削平
        int size1 = stack1.size();
        int size2 = stack2.size();
        int size = Math.abs(size1-size2);
        if(size1 > size2) {
            while (size != 0) {
                stack1.pop();
                size--;
            }
        }else {
            while (size != 0) {
                stack2.pop();
                size--;
            }
        }
        //3.同时出栈
        while(!stack1.empty() && !stack2.empty()) {
            if(stack1.peek() == stack2.peek()) {
                break;
            }
            stack1.pop();
            stack2.pop();
        }
        return stack1.pop();
    }

    /**
     * 判断一棵树是否为安全二叉树
     * 第二种思路：1.左为空，有不为空---不是 2.左为空，并且下一层都为空/非空
     * @param root
     * @return
     */
    public boolean isCompleteTree(TreeNode root) {
        if(root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur == null) {
                break;
            }
            queue.offer(cur.left);
            queue.offer(cur.right);
        }

        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur != null) {
                return false;
            }
        }
        return true;
    }

    /**
     * 根据二叉树创建字符串
     * @param root
     * @return
     */
    public String tree2str(TreeNode root) {
        StringBuilder sbu = new StringBuilder();
        tree2trChild(root,sbu);
        return sbu.toString();
    }
    public void tree2trChild(TreeNode root,StringBuilder sbu) {
        if(root == null) {
            return;
        }
        //1.根
        sbu.append(root.val);
        //2.左
        if(root.left != null) {
            sbu.append("(");
            tree2trChild(root.left,sbu);
            sbu.append(")");
        }else {
            if(root.right == null) {
                return;
            }else {
                sbu.append("()");
            }
        }
        //3.右
        if(root.right != null) {
            sbu.append("(");
            tree2trChild(root.right,sbu);
            sbu.append(")");
        }else {
            return;
        }
    }
    /**
     * 前序遍历的非递归实现
     */
    public List<Character> preorderTraversal(TreeNode root) {
        List<Character> list = new LinkedList<>();
        if(root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();

        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                list.add(root.val);
                cur = cur.left;
            }
            cur = stack.pop().right;

        }

        return list;
    }
    /**
     * 中序遍历非递归实现
     */
    public List<Character> inorderTraversal(TreeNode root) {
        List<Character> list = new LinkedList<>();
        if(root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.pop();
            list.add(top.val);
            cur = top.right;
        }
        return list;
    }

    /**
     * 非递归实现后序遍历
     * @param root
     * @return
     */
    public List<Character> postorderTraversal(TreeNode root) {
        List<Character> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        TreeNode pop = null;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.peek();
            if(top.right == null || top.right == pop) {
                list.add(top.val);
                pop = top;
                stack.pop();
            }else {
                cur = top.right;
            }
        }
        return list;
    }

    /**
     * 根据前序和中序遍历创建二叉树
     */
    public int preIndex = 0;//遍历前序遍历
    public TreeNode buildTree(char[] preorder, char[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }

    private TreeNode buildTreeChild(char[] preorder,char[] inorder,int inBegin,int inEnd) {
        if(inBegin > inEnd) {
            return null;
        }
        //1.创造根结点
        TreeNode root = new TreeNode(preorder[preIndex]);
        int rootIndex = findRootIndex(inorder,inBegin,inEnd,preorder[preIndex]);
        preIndex++;//找下一个根
        //创建左数和右数
        root.left = buildTreeChild(preorder,inorder,inBegin,rootIndex-1);
        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inEnd);

        return root;
    }
    //3.找根节点下标
    private int findRootIndex(char[] inorder,int inBegin,int inEnd,int key) {
        for(int i = inBegin;i <= inEnd;i++ ) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 中序和后序遍历创建二叉树，创建的时候以后序
     */

    public int postIndex;
    public TreeNode buildTree2(char[] inorder, char[] postorder) {
        postIndex = inorder.length-1;
        return buildTreeChild(postorder,inorder,0,inorder.length-1);
    }
    private TreeNode buildTreeChild2(char[] postorder,char[] inorder,int inBegin,int inEnd) {
        if(inBegin > inEnd) {
            return null;
        }
        //1.创造根结点
        TreeNode root = new TreeNode(postorder[postIndex]);
        int rootIndex = findRootIndex2(inorder,inBegin,inEnd,postorder[postIndex]);
        postIndex--;//找下一个根
        //创建左数和右数
        root.right = buildTreeChild2(postorder,inorder,rootIndex+1,inEnd);
        root.left = buildTreeChild2(postorder,inorder,inBegin,rootIndex-1);



        return root;
    }
    //3.找根节点下标
    private int findRootIndex2(char[] inorder,int inBegin,int inEnd,int key) {
        for(int i = inBegin;i <= inEnd;i++ ) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }


}
